#! /usr/bin/python3
# -*- coding: utf-8 -*-

# This code shows an example of text translation from English to Simplified-Chinese.
# This code runs on Python 2.7.x and Python 3.x.
# You may install `requests` to run this code: pip install requests
# Please refer to `https://api.fanyi.baidu.com/doc/21` for complete api document

import requests
import random
import json
import pyperclip
from hashlib import md5
import time
from threading import Thread
import os
import subprocess

# 造一个线程用于退出，使用全局变量A通信。
def foo():
    global A   # 全局变量要在子函数中声明
    a = ''
    while a != 'q':
        a = input() # 等待用户输入
    A = a
    return A

def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()

# query = 'Hello World! This is 1st paragraph.\nThis is 2nd paragraph.'
# 处理选择缓冲区中的内容函数：
def  inputs():
    # os.popen 执行linux命令，返回输出结果
    cmd   = 'xclip -out'
    query_ = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines()
    query = " "
    for i in range(len(query_)):
        query += query_[i].decode('utf-8') # [b'str...',...]是btype类型的数据，需要转为str普通字符串
    # 结尾是句号的不合并行，结尾不是句号的合并成一句
    query = query.replace(".\n","\*")
    query = query.replace("\n"," ")
    query = query.replace("\*",".\n")
    query = query.replace("\r"," ")
    query = query.replace("\t"," ")
    for i in range(8,2,-1):
        query = query.replace(" "*i," ")
    query = query.replace("‐ ","")
    # print(query)
    return query
if __name__== '__main__':
    A = 'a'
    thd = Thread(target=foo) # 开启一个线程
    thd.daemon = True
    thd.start()
    
    # 百度翻译api接口所需参数表
    # Set your own appid/appkey.
    appid = '20211105000991769'
    appkey = 'BGMumlXi6QJWE0mmcjCd'
    
    # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
    from_lang = 'en'
    to_lang =  'zh'
    
    endpoint = 'http://api.fanyi.baidu.com'
    path = '/api/trans/vip/translate'
    url = endpoint + path
    
    q0 = '_' # 记录上一次选择缓冲区的内容
    while 1:
        # 当输入q给全局变量A时，退出
        if A == 'q':
            break

        try:
            q1 = inputs()
            # 当选择缓冲区没有内容或者只有空格符时，跳出本次循环
            if q1 == '' or q1== ' ':
                time.sleep(1)
                continue

            salt = random.randint(32768, 65536) # 返回指定范围内的一个整数
            sign = make_md5(appid + q1 + str(salt) + appkey) # 格式化，使用ytf-8编码
            if len(q0) != len(q1):
                # Generate salt and sign
                # Build request
                headers = {'Content-Type': 'application/x-www-form-urlencoded'}
                payload = {'appid': appid, 'q': q1, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
                
                # Send request
                r = requests.post(url, params=payload, headers=headers)
                result = r.json()
                
                # Show response
                for i in range(len(result['trans_result'])):
                # 打印待翻译内容
                    print('    ',end="")
                    print(result['trans_result'][i]['src'])
                # 打印翻译结果
                    print('    ',end="")
                    print(result['trans_result'][i]['dst'])
                print('-------------- 等待中,退出(q) ------------')
                # 记录待翻译内容，用于下次循环比较
                q0 = q1
            else:
                pass
        except:
            pass
        time.sleep(1)

